package com.faf.ui;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.faf.dao.impl.UserDaoImpl;
import com.faf.tools.PHOUtils;
import com.faf.tools.RSAUtils;

/**
 * Servlet implementation class UserRegister
 */
@WebServlet("/UserRegister")
public class UserRegister extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//设置中文格式
		response.setContentType("text/html;charset=utf-8"); 
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		//读取register.jsp中的个信息
		String user_number = request.getParameter("user_number");
		String user_pwd = request.getParameter("user_pwd");
		String user_rsa = RSAUtils.publicEncrytype(user_pwd);
		String user_phone = request.getParameter("user_phone");
		String submit = request.getParameter("submit");
		//跟新用户信息
		UserDaoImpl user = new UserDaoImpl();
		//添加用户信息的数据库语句
		String sql_register = "insert into user (userPassword,userNumber,userPhone)values(?,?,?) ";
		String sql_check = "select userId from user where userNumber = ? ";
		String json = "";
		try {
			UserDaoImpl udi = new UserDaoImpl();
			//如果用户名输入是手机号会提示错误
			if(submit.equals("1")){
				System.out.println("用户名正在存入");
				user.executeUpdate(sql_register,user_rsa,user_number,user_phone);
				System.out.println("用户名存入成功");
				json = "{\"code\":"+1+"}";
				response.getWriter().print(json);
			}
			else if(!PHOUtils.checkNickName(user_number)){
				System.out.println("手机号不可做作用户名");
				json = "{\"code\":"+-1+"}";
				response.getWriter().print(json);
			}
			else if(user_number.equals(udi.getUserByNumber(user_number).getUserNumber())){
				System.out.println("用户名已存在");
				json = "{\"code\":"+0+"}";
				response.getWriter().print(json);
			}
			else if(PHOUtils.checkNickName(user_phone)){
				
				System.out.println("请使用正确的手机号*"+PHOUtils.checkNickName(user_phone));
				json = "{\"code\":"+-2+"}";
				response.getWriter().print(json);
			}
			else if(!PHOUtils.checkNickName(user_phone)){
				json = "{\"code\":"+2+"}";
				response.getWriter().print(json);
			}
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
